<template>
  <div class="container">
    <el-scrollbar>
      <div class="left_menu">
        <el-menu default-active="0" @select="selectMenu">
          <div class="menu_item" v-for="(item, index) in menuList" :key="index">
            <el-sub-menu :index="index + ''" v-if="item.child">
              <template #title>
                <el-icon>
                  <Headset />
                </el-icon>
                <span>{{ item.name }}</span>
                <el-icon
                  class="add_plus"
                  v-show="item.isMySongSheet"
                  size="12"
                  @click.stop="addSongSheet"
                  ><Plus
                /></el-icon>
              </template>
              <el-menu-item-group
                :title="item.child.length ? '' : '什么也没有，快去发现好音乐'"
              >
                <el-menu-item
                  @mouseenter="menuItemEnter(e)"
                  @mouseleave="menuItemLeave(e)"
                  v-for="(e, i) in item.child"
                  :index="index + '-' + i"
                >
                  <div class="left">
                    <el-image
                      style="width: 46px; height: 46px"
                      :src="baseUrl + e.image"
                    />
                    <div class="song_sheet_info">
                      <span class="name">{{ e.title }}</span>
                      <span class="number">{{ e.list?.length }}首</span>
                    </div>
                  </div>

                  <el-popconfirm
                    title="确定删除个歌单？"
                    @confirm="deleteSongSheet(e)"
                  >
                    <template #reference>
                      <el-icon v-show="e.hover && !item.isNotDel">
                        <Delete />
                      </el-icon>
                    </template>
                  </el-popconfirm>
                </el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
            <el-menu-item :index="index + ''" v-else>
              <el-icon>
                <component :is="item.icon"></component>
              </el-icon>
              <span>{{ item.name }}</span>
            </el-menu-item>
          </div>
        </el-menu>
      </div>
    </el-scrollbar>
    <div class="right_list">
      <div class="top">
        <div class="cover">
          <el-image :src="baseUrl + menuInfo.cover" />
        </div>
        <div class="info">
          <div class="info_top">
            <span>{{ menuInfo.title }}</span>
            <div class="user_info">
              <el-avatar
                shape="square"
                :size="40"
                :src="baseUrl + menuInfo.avatar"
              />
              <span class="user_name">{{ menuInfo.nickName }}</span>
              <span class="create_time">{{ menuInfo.createTime }} 创建</span>
            </div>
          </div>
          <div class="btns">
            <el-button type="primary" icon="CaretRight" @click="playAll"
              >全部播放</el-button
            >
          </div>
        </div>
      </div>
      <div class="center">
        <span>歌曲列表</span>
        <span>{{ "共" + tableData.length + "首" }}</span>
      </div>
      <div class="list">
        <el-table
          height="100%"
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="index" align="center" width="60" />
          <el-table-column width="60" align="center">
            <template #default="scope">
              <i
                @click="play(scope.row, scope.$index)"
                class="iconfont icon-bofang"
              ></i>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="歌曲">
            <template #default="scope">
              <div
                @click="onMusic(scope.row)"
                style="cursor: pointer !important"
              >
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="歌手" width="300">
            <template #default="scope">
              <div
                @click="onUser(scope.row)"
                style="cursor: pointer !important"
              >
                {{ scope.row.user?.nickname }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时间" width="200">
            <template #default="scope">
              <span>{{ timeFilter(scope.row.duration) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加歌单 -->
    <el-dialog v-model="addSongsShow" title="添加歌单" width="30%">
      <div class="addDialog">
        <el-input v-model="addInfo.title" placeholder="请输入歌单名称" />
        <el-input
          type="textarea"
          v-model="addInfo.desc"
          placeholder="请输入歌单描述"
        />
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/api/file/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="addInfo.image" :src="addInfo.image" class="avatar" />
          <span v-else>视频封面</span>
        </el-upload>
        <div class="btn">
          <el-button @click="addSongs">添加</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  songsMy,
  songsAdd,
  songsDel,
  musicCollectMy,
  songsCollectMy,
} from "@/http/api";
import { ElMessage } from "element-plus";
import { PersistentStore } from "@/stores";

const persistentStore = PersistentStore();
const baseUrl = import.meta.env.VITE_API_URL;
const router = useRouter();
const addInfo = ref({});
const addSongsShow = ref(false);
const selSongId = ref("");
const menuInfo = ref({
  title: "我喜欢",
  avatar: computed(() => persistentStore.userInfo.avatar),
  createTime: computed(() => persistentStore.userInfo.create_time),
  nickName: computed(() => persistentStore.userInfo.nickname),
});
const menuList = ref([
  {
    name: "我喜欢",
    icon: "Star",
  },
  // {
  //   name: "已下载",
  //   icon: "Download",
  // },
  // {
  //   name: "最近播放",
  //   icon: "Timer",
  // },
  {
    name: "我的歌单",
    isMySongSheet: true,
    child: [],
  },
  {
    isNotDel: true,
    name: "收藏的歌单",
    child: [],
  },
]);

const tableData = ref([
  {
    name: "歌曲名",
    singer: "歌手名",
    time: 166,
  },
]);

onMounted(() => {
  getMyLike();
  getSongs();
  getSongsCollect();
});

const onMusic = (e) => {
  router.push({
    name: "music",
    query: {
      id: e.id,
    },
  });
};

const onUser = (e) => {
  router.push({
    name: "user",
    query: {
      id: e.user.id,
    },
  });
};

const getSongsCollect = async () => {
  const { data } = await songsCollectMy();
  menuList.value[2].child = data.songs_collect;
};

const playAll = () => {
  const url = router.resolve("/play_music");
  const arr = { id: selSongId.value, index: 0, list: tableData.value };
  persistentStore.setSongListInfo(arr);
  window.open(url.href, url.href).postMessage(JSON.stringify(arr));
};

const play = (e, i) => {
  const url = router.resolve("/play_music");
  const arr = { id: selSongId.value, index: i, list: tableData.value };
  persistentStore.setSongListInfo(arr);
  window.open(url.href, url.href).postMessage(JSON.stringify(arr));
};

const handleAvatarSuccess = (e) => {
  addInfo.value.image = e.url[0];
};

const beforeAvatarUpload = () => {};

const tableRowClassName = ({ rowIndex }) => {
  if (rowIndex % 2 == 0) {
    return "primary_row";
  }
  return "";
};

const addSongs = async () => {
  if (!addInfo.value.title) {
    ElMessage.error("请输入歌单名称");
  }
  const { code, data, msg } = await songsAdd(addInfo.value);
  if (code == 200) {
    addSongsShow.value = false;
    getSongs();
    return;
  }
  ElMessage.error(msg);
};

const selectMenu = (e) => {
  const menuSel = e.split("-");
  if (menuSel.length > 1) {
    const info = menuList.value[menuSel[0]].child[menuSel[1]];
    console.log(info);
    tableData.value = info.list;
    selSongId.value = info.id;
    menuInfo.value = {
      title: info.title,
      createTime: info.create_time,
      cover: info.image,
    };
    if (menuSel[0] == "1") {
      menuInfo.value.avatar = persistentStore.userInfo.avatar;
      menuInfo.value.nickName = persistentStore.userInfo.nickname;
    } else {
      menuInfo.value.avatar = info.user.avatar;
      menuInfo.value.nickName = info.user.nickname;
    }
  } else {
    selSongId.value = "";
    if (menuSel[0] == 0) {
      menuInfo.value = {
        title: "我喜欢",
        avatar: persistentStore.userInfo.avatar,
        createTime: persistentStore.userInfo.create_time,
        nickName: persistentStore.userInfo.nickname,
      };
      getMyLike();
    }
  }
};

const getMyLike = async () => {
  const { data } = await musicCollectMy();
  tableData.value = data.music;
  menuInfo.value.cover = data.music[0].image;
};

const getSongs = async () => {
  const { data } = await songsMy();
  menuList.value[1].child = data.songs;
};

const addSongSheet = () => {
  addSongsShow.value = true;
};

const menuItemEnter = (e) => {
  e.hover = true;
};

const menuItemLeave = (e) => {
  e.hover = false;
};

const deleteSongSheet = async (e) => {
  console.log(e);
  const { data } = await songsDel({
    id: e.id,
  });
  getSongs();
};

const timeFilter = (e) => {
  let timeFormat = "00:00";
  if (e) {
    let minutes = Math.floor(e / 60);
    let second = e % 60;
    timeFormat =
      minutes.toString().padStart(2, "0") +
      ":" +
      second.toString().padStart(2, "0");
  }
  return timeFormat;
};
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>

<style></style>
